import axios from "axios";
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import type { UserInfo } from "@/types/userTypes/userTypes.ts";
import Nprogress from "nprogress";

import { getUserInfo } from "@/utils/localStorage.ts";

export const baseURL: string = import.meta.env.VITE_APP_SERVER;

// 创建axios的实例
const request: AxiosInstance = axios.create({
   baseURL,
   timeout: 10000,
});

// 添加请求拦截器
request.interceptors.request.use(function(config: InternalAxiosRequestConfig) {
   // 在发送请求之前做些什么
   const userInfo: UserInfo = getUserInfo<UserInfo>();
   if (userInfo) {
      config.headers.authorization = `Bearer ${userInfo.token}`;
   }
   Nprogress.start();
   return config;
}, function(error) {
   // 对请求错误做些什么
   return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function(response: AxiosResponse) {
   // 2xx 范围内的状态码都会触发该函数。对响应数据做点什么
   Nprogress.done();
   if (response.data && response.data.code !== 10000) {
      return Promise.reject(new Error(response.data.message));
   }
   return response.data;
}, function(error) {
   // 超出 2xx 范围的状态码都会触发该函数。对响应错误做点什么
   Nprogress.done();
   return Promise.reject(error);
});

export default request;

